package ggze.tool;

import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

public class ImgUtils {
    public String uploadImage(MultipartFile multipartFile, String path) throws Exception {
        String day= TimeUtils.getTimeFormat().substring(0,10);
        String pathDay=path+"//"+ day;
        File f = new File(pathDay);
        if(!f.exists()) {
            f.mkdirs(); //创建目
        }
        path=pathDay;
        if (!StringUtils.isEmpty(multipartFile) && multipartFile.getSize()>0){
            String filename = multipartFile.getOriginalFilename();
            String suffix = filename.substring(filename.lastIndexOf(".") + 1);
            if (filename.endsWith("jpg")||filename.endsWith("png")||filename.endsWith("JPG")||filename.endsWith("PNG")){
                String names= TimeUtils.getTimeStmp() +"."+suffix;
                names=names.toLowerCase();
                String realPath =path+"/"+names;
                File newfile = new File(realPath);
                try {
                    multipartFile.transferTo(newfile);
                    return day+"/"+names;
                } catch (IOException e) {
                    e.printStackTrace();
                    return "error";
                }
            }else {

                return "typeError";
            }
        }else {
            return "nullError";
        }
    }
    /*public static void main(String[] args){
        System.out.println(TimeUtils.getTimeFormat().substring(0,10));
    }*/
}
